const express = require("express")
const router = express.Router()
const {User} = require("../../models")
const {Op} = require("sequelize")
const {success} = require("../../utils/response")
const {BadRequest, NotFound, Unauthorized} = require("http-errors")
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

router.post("/sign_in", async (req, res, next) => {
    try {
        const {login, password} = req.body

        if(!login) {
            throw new BadRequest("邮箱/用户名必须填写")
        }

        if(!password) {
            throw new BadRequest("密码必须填写")
        }

        const condition = {
            where: {
                [Op.or]: [
                    {email: login},
                    {name: login},
                ]
            }
        }

        const user = await User.findOne(condition)

        if(!user) {
            throw new NotFound("用户有不存在，无法登录")
        }

        // 验证密码
        const isPasswordValid = bcrypt.compareSync(password, user.password)
        if(!isPasswordValid) {
            throw new Unauthorized('密码错误。');
        }

        if(user.role !== 100) {
            throw new Unauthorized("您没有权限登录管理员后台")
        }

        const token = jwt.sign({
            userId: user.id
        }, process.env.SECRET, {expiresIn: '30d'})

        success(res, "登陆成功", {token})
    } catch(err) {
        next(err)
    }
})

module.exports = router